import XLSX, {
	utils
} from 'xlsx'
const EXCEL = {
	exportSheetFromArray(option) {
		var fileName = option[0].name + '.' + option[0].suffix;
		var suffix = option[0].suffix;
		var workBook = utils.book_new();
		option.forEach(item => {
			const config = Object.assign({}, {
				name: 'demo',
				suffix: 'xlsx'
			}, item)
			const {
				title,
				body,
				name,
				suffix,
				sheetName,
				merges
			} = config;
			//const fileName = name + '.' + suffix;
			//const workBook = utils.book_new(); //创建workBook
			const workSheet = utils.aoa_to_sheet(body); //将数组转换成workSheet
			workSheet['!merges'] = merges;
			utils.book_append_sheet(workBook, workSheet, sheetName);
			console.log("workSheet---->", workSheet)
		})
		XLSX.writeFile(workBook, fileName, {
			bookType: suffix,
			type: 'buffer'
		})
	},
	// 导出Excel方法
	/**
	 * @description                  依据数据导出表格，一般是根据查询出的数据导出表格
	 * @param {Object} option        Object--配置对象
	 * @param option.title      Array--表头，即表格首行展示的内容，如：['姓名','年龄','性别','地址']
	 * @param option.body       Array--表格内容，二维数组，每一行的内容为一个数组，与表头对应，如:[['王小虎',28,'男','aa'],['王大虎',29,'男','aa']]
	 * @param option.name       String--文件名，如:'demo'
	 * @param option.suffix     String--文件后缀名，如'csv'
	 * @param option.merges     Array--表格的单元格合并信息，如[
	      { s: { r: 0, c: 0 }, e: { r: 1, c: 0 } },-----表示A1和A2单元格合并
	      { s: { r: 0, c: 1 }, e: { r: 0, c: 2 } },-----表示B1和C1单元格合并
	      { s: { r: 0, c: 3 }, e: { r: 0, c: 4 } },-----表示D1和E1单元格合并
	      { s: { r: 0, c: 5 }, e: { r: 1, c: 5 } }-----表示F1和F2单元格合并
	    ]------s:start,e:end,r:row,c:cell;
	 */
	exportFromArray(option) {
		const config = Object.assign({}, {
			name: 'demo',
			suffix: 'xlsx'
		}, option)
		const {
			title,
			body,
			name,
			suffix,
			merges
		} = config;
		const fileName = name + '.' + suffix;
		const workBook = utils.book_new(); //创建workBook
		const workSheet = utils.aoa_to_sheet(body); //将数组转换成workSheet
		workSheet['!merges'] = merges;
		utils.book_append_sheet(workBook, workSheet, name);
		console.log("workSheet---->", workSheet)
		XLSX.writeFile(workBook, fileName, {
			bookType: suffix,
			type: 'buffer'
		})
	},
	/**
	 * @description                      依据网页中的表格导出文件，只导出网页中的表格数据
	 * @param {Object} option            配置对象
	 * @param {string} option.id         表格在dom中的id,必传
	 * @param {string} option.name       String--文件名，如:'demo'
	 * @param {string} option.suffix     String--文件后缀名，如'csv'
	 */
	exportFromTable(option) {
		const config = Object.assign({}, {
				name: 'demo',
				suffix: 'csv',
				sheetName: '信息表'
			}, option),
			{
				id,
				name,
				suffix,
				merges,
				sheetName
			} = config,
			workBook = utils.book_new(),
			workSheet = utils.table_to_sheet(document.getElementById(id)),
			fileName = name + '.' + suffix;
		workSheet['!merges'] = merges;
		console.log("workSheet---->", workSheet)
		utils.book_append_sheet(workBook, workSheet, sheetName);
		XLSX.writeFile(workBook, fileName, {
			bookType: suffix,
			type: 'buffer'
		})
	},
	/**
	 * @description  解析表格文件数据，返回表格中内容，目前暂不支持导入有单元格合并的表格
	 * @param    {Object} file    导入的文件，二进制数据流
	 * @returns  {Object} data    返回的表格数据
	 * @returns  {Array}  data.title   表头
	 * @returns  {Array}  data.body    表格数据
	 */
	/**
	 * @description  解析表格文件数据，返回表格中内容，目前暂不支持导入有单元格合并的表格
	 * @param {Object} file		导入的文件，二进制数据流
	 * @param {Object} index	sheet标识
	 * @param {Object} startCol	读取开始的列数
	 * @param {Object} header	表头开始坐标
	 * @returns  {Object} data    返回的表格数据
	 * @returns  {Array}  data.title   表头
	 * @returns  {Array}  data.body    表格数据
	 */
	async importFromLocal(file, index, startCol, header) {
		if (index == undefined) { //默认读取第一个sheet
			index = 0
		}
		var opt = {
			defval: "",
			header: header
		}
		const workBook = await this.readerWorkBookFromLocal(file),
			workSheet = workBook.Sheets[workBook.SheetNames[index]],
			data = {};
		// 开始读取的列数
		if (startCol != undefined && startCol != null && startCol != "") {
			opt.range = workSheet["!ref"].replace('A1', startCol)
		}
		console.log("workSheet----》", workBook, workSheet)
		const content = utils.sheet_to_json(workSheet, opt)
		data.title = Object.keys(content[0]);
		data.body = content;
		return data;
	},
	/**
	 * 获取多个sheet  若fistIndex为 -1 获取所有
	 * @param {Object} file
	 * @param {Object} fistIndex	
	 * @param {Object} lastIndex
	 * @param {Object} startCol  	读取开始的列数
	 * @param {Object} header		表头开始坐标
	 */
	async importSheets(file, fistIndex, lastIndex, startCol, header) {
		var opt = {
			defval: "",
			header: header
		}
		const workBook = await this.readerWorkBookFromLocal(file)
		const sheets = workBook.SheetNames
		const data = [];
		if (fistIndex == null || fistIndex == -1 || lastIndex == -1) {
			fistIndex = 0
			lastIndex = sheets.length
		}
		if (fistIndex > sheets.length || fistIndex > lastIndex) {
			return []
		} else {
			if (lastIndex > sheets.length) {
				lastIndex = sheets.length
			}
			for (let i = fistIndex; i < lastIndex; i++) {
				var temp = {
					sheetName: sheets[i],
					body: []
				}
				const workSheet = workBook.Sheets[sheets[i]]
				// 开始读取的列数
				if (startCol != undefined && startCol != null && startCol != "") {
					opt.range = workSheet["!ref"].replace('A1', startCol)
				}
				console.log("workSheet-------->", workSheet)
				const content = utils.sheet_to_json(workSheet, opt)
				temp.body = content;
				data.push(temp)
			}
			return data;
		}

	},
	/**
	 * 获取入驻申请中、导入数据表
	 * @param {Object} file
	 */
	async importFromLocalByData(file) {
		var opt = {
			defval: "",
		}
		const workBook = await this.readerWorkBookFromLocal(file)
		const sheets = workBook.SheetNames
		const data = [];
		sheets.forEach(sheet => {
			const workSheet = workBook.Sheets[sheet]
			// 开始读取的列数
			opt.range = "A1:B4"
			opt.header = 1
			const content1 = utils.sheet_to_json(workSheet, opt)
			var temp = {
				tableName: content1[0][1],
				domain: content1[1][1],
				purpose: content1[2][1],
				cycleType: content1[3][1]
			}

			opt.range = workSheet["!ref"].replace('A1', 'A5')
			opt.header = 0
			const content2 = utils.sheet_to_json(workSheet, opt)
			temp.title = Object.keys(content2[0]),
				temp.body = content2

			data.push(temp)
		})
		return data;
	},
	/**
	 * 替换每行数据的key值 by columns
	 */
	handleInfoByColumns(content, columns, that) {
		console.log(content, columns)
		var temp = []
		var key = [];
		columns.forEach(item => {
			key.push(item.title)
		})
		content.forEach(item => {
			var temp2 = {}
			key.forEach(i => {
				var c = item[i]
				if (c != undefined) {
					that.$set(temp2, columns.find(e => e.title == i).key, item[i])
				} else {
					that.$set(temp2, columns.find(e => e.title == i).key, "")
				}
			})
			temp.push(temp2)
		})

		return temp
	},
	/**
	 * @param {Object} content excel获取的数据
	 * @param {Object} columns 需要转换的表格数据
	 * @param {Object} that
	 */
	handleInfoByContent(content, columns, that) {
		var temp = []
		var key = [];
		key = Object.keys(content[0]);
		content.forEach(item => {
			var temp2 = {}
			key.forEach(i => {
				var c = columns.find(e => e.title == i.trim())
				if (c != undefined) {
					that.$set(temp2, c.key, item[i])
				} else {
					that.$set(temp2, i, item[i])
				}
			})
			temp.push(temp2)
		})
		return temp
	},
	/**
	 * 转换第一列为Key， 后续为value
	 * @param {Object} content
	 * @param {Object} that
	 */
	handleInfoToColKeyVal(content, that) {
		console.log(content)
		if (content != undefined && content != null && content.length > 0) {
			let len = content[0].length
			var temp = []
			for (let i = 1; i < len; i++) {
				var key = {
					service: {}
				}
				content.forEach(item => {
					if (item[i] !== "" && item[0] !== "") {
						if (item[0].indexOf('-') != -1) {
							that.$set(key.service, item[0], item[i])
						} else {
							that.$set(key, item[0], item[i])
						}
					}
				})
				// console.log("item[i]----》",content[0][0],key[content[0][0]])
				// console.log("key--->",key)
				if (key.service != {} && key[content[0][0]] != undefined) {
					temp.push(key)
				}
			}
			console.log("temp---->", JSON.stringify(temp))
			return temp
		}
	},
	/**
	 * @description              本地读取文件的方法
	 * @param {Object} file      文件流
	 */
	readerWorkBookFromLocal(file) {
		const reader = new FileReader();
		reader.readAsBinaryString(file);
		return new Promise(function(resolve, reject) {
			reader.onload = function(e) {
				const fileData = e.target.result;
				if (reader.readyState === 2) {
					const workBook = XLSX.read(fileData, {
						type: 'binary'
					});
					resolve(workBook);
				} else {
					reject('读取文件失败');
				}
			}
		})
	},
	exportSheetFromArray(option) {
		var fileName = option[0].name + '.' + option[0].suffix;
		var suffix = option[0].suffix;
		var workBook = utils.book_new();
		option.forEach(item => {
			const config = Object.assign({}, {
				name: 'demo',
				suffix: 'xlsx'
			}, item)
			const {
				title,
				body,
				name,
				suffix,
				sheetName,
				merges
			} = config;
			//const fileName = name + '.' + suffix;
			//const workBook = utils.book_new(); //创建workBook
			const workSheet = utils.aoa_to_sheet(body); //将数组转换成workSheet
			workSheet['!merges'] = merges;
			utils.book_append_sheet(workBook, workSheet, sheetName);
			console.log("workSheet---->", workSheet)
		})
		XLSX.writeFile(workBook, fileName, {
			bookType: suffix,
			type: 'buffer'
		})
	},

}

export default EXCEL;
